package cn.com.yang.thread;

/**
 * wait()与notify()的使用
 * wait()只能在同步代码块或者同步方法中被调用
 * TODO
 * @author yangyijin
 * @since 2024年5月6日-上午10:23:47
 */
public class WaitNotifyExample {  
    private static final Object lock = new Object();  
  
    public static void main(String[] args) {  
        Thread producer = new Thread(() -> {  
            synchronized (lock) {  
                for (int i = 0; i < 5; i++) {  
                    System.out.println("Produced: " + i);  
                    try {  
                        Thread.sleep(1000);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                    lock.notify(); // 唤醒一个在 lock 对象上等待的线程  
                }  
            }  
        });  
  
        Thread consumer = new Thread(() -> {  
            for (int i = 0; i < 5; i++) {  
                synchronized (lock) {  
                    try {  
                        lock.wait(); // 当前线程等待，直到其他线程调用 lock.notify() 或 lock.notifyAll()  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
                System.out.println("Consumed: " + i);  
            }  
        });  
  
        producer.start();  
        consumer.start();  
    }  
}
